package com.sso.web;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sso.service.UserService;
import com.sso.utils.HttpClientPost;
import com.sso.utils.Result;
import com.sso.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sso.pojo.User;

/**
 * @author alex
 * @decription 用户认证的controller
 */
@Controller
@RequestMapping()
public class SsoController {
    /**
     * 单位是秒
     */
    private static final Integer MAX_AGE = 30 * 60;
    private static final Integer REDIRECT_STATUS = 302;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "/signIn")
    public void signIn(HttpServletRequest request, HttpServletResponse response) {
        String returnUrl = request.getParameter("returnUrl");
        String name = request.getParameter("userName");
        String passWd = request.getParameter("password");
        //TODO 验证登录信息
        String token = TokenUtil.createToken(name);
        Cookie clientCookie = new Cookie("token", token);
        clientCookie.setMaxAge(MAX_AGE);
        clientCookie.setPath("/");
        response.addCookie(clientCookie);
        response.setHeader("Authentication", token);
        response.addHeader("location", request.getParameter("returnUrl"));
        response.setStatus(REDIRECT_STATUS);
        //TODO 将token保存到redis，过期时间30分钟
    }

    @RequestMapping(value = "/checkLogin")
    public void checkLogin(HttpServletRequest request, HttpServletResponse response) {
        //POST转发请求
        String returnUrl = request.getParameter("returnUrl");
        String token = getCookies("token", request);
        HttpClientPost post = new HttpClientPost(response);
        if (StringUtils.isEmpty(token)) {

            post.putParameter("code","1");
        } else {
            post.putParameter("token",token);
            post.putParameter("code","0");
        }
        try {
            post.sendByPost(returnUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        response.addHeader("location", returnUrl);
//        response.setStatus(REDIRECT_STATUS);

    }

    @RequestMapping(value = "/checkToken", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public Result checkToken(HttpServletRequest request, HttpServletResponse response) {
        String tokenVal = request.getParameter("token");
        //TODO 在redis查询是否有用户信息
        //TODO token正常，在redis更新token过期时间
        return Result.buildIsOk("success");

    }

    /**
     * 设置或者更新缓存  缓存默认保存半个小时
     *
     * @param key
     * @param dbUser
     */
    public void updateCache(String key, User dbUser) {
        //设置到缓存 默认半个小时
        redisTemplate.opsForValue().set(key, dbUser, 60 * 30, TimeUnit.SECONDS);
    }

    /**
     * 获取cookie
     *
     * @param key
     * @param request
     * @return
     */
    public static String getCookies(String key, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length < 0) {
            return null;
        }

        String tokenVal = "";
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (!StringUtils.isEmpty(name) && key.equals(name)) {
                tokenVal = cookie.getValue();
            }
        }

        return tokenVal;
    }
}
